package com.lhx.wechat.utils;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

/**
 *
 * 获取 access_token
 */
public class WechatAccessTokenUtil {

	private static final Logger logger = LoggerFactory.getLogger(WechatAccessTokenUtil.class);

	// 获取access_token的接口地址（GET） 限2000（次/天）
	private final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?"
			+ "grant_type=client_credential&appid=%s&secret=%s";

	/**
	 * 获取 access_token ， 需要业务模块自行做 全局缓存
	 * 
	 * @param appId
	 * @return
	 */
	public static String getToken(String appId) {
		String url = String.format(ACCESS_TOKEN_URL, appId, "3d862c8b692de7c5881e487e76bd6f38");
		try {
			CustomerSimpleHttpClient simpleHttpClient = new CustomerSimpleHttpClient();
			String body = simpleHttpClient.get(url);
			logger.info("get token:" + body);
			Map<String, String> map = JSON.parseObject(body, new TypeReference<Map<String, String>>() {
			});
			return map.get("access_token");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
}
